package com.neusoft.shopping.manager.dao;
import com.neusoft.shopping.manager.comm.Page;
import com.neusoft.shopping.manager.entity.GoodsEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class GoodsDaAOImpl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Integer queryCount(){
        String sql= "select count(*) from goodsinfo";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    public Page<GoodsEntity> queryAll(Page<GoodsEntity> page){
        page.setTotalCount(queryCount());
        String sql = "select * from goodsinfo ";
        RowMapper<GoodsEntity> rowMapper = new BeanPropertyRowMapper<>(GoodsEntity.class);
        List<GoodsEntity> list = jdbcTemplate.query(sql,rowMapper);
        page.setArrys(list);
        return page;
    }

    public List<GoodsEntity> queryAlll(){
        String sql = "select * from goodsinfo ";
        RowMapper<GoodsEntity> rowMapper = new BeanPropertyRowMapper<>(GoodsEntity.class);
        return jdbcTemplate.query(sql,rowMapper);
    }

    public GoodsEntity querylast(){
        String sql = "select * from goodsinfo order by goodsno DESC limit 1";
        RowMapper<GoodsEntity> rowMapper = new BeanPropertyRowMapper<>(GoodsEntity.class);
        return jdbcTemplate.queryForObject(sql,rowMapper);
    }

    public GoodsEntity getGoodsByOne(Integer goodsno){
        String sql = "select * from goodsinfo where goodsno=?";
        RowMapper<GoodsEntity> rowMapper = new BeanPropertyRowMapper<>(GoodsEntity.class);
        return jdbcTemplate.queryForObject(sql,rowMapper,goodsno);
    }


    public int add_Goods(GoodsEntity g){
        String sql = "insert into goodsinfo values(null,?,?,?,?,?)";
        return jdbcTemplate.update(sql,g.getGoodsname(),g.getGoodsunit(),g.getGoodsprice(),g.getGoodstype(),g.getDetails());
    }

    public int update_Goods(GoodsEntity g){
        String sql = "update goodsinfo set goodsname=?,goodsprice=?,goodsunit=?,goodstype=?,details=? where goodsno=?";
        return jdbcTemplate.update(sql,g.getGoodsname(),g.getGoodsprice(),g.getGoodsunit(),g.getGoodstype(),g.getDetails(),g.getGoodsno());
    }

    public int del_Goods(Integer goodsno)
    {
        String sql = "delete from goodsinfo where goodsno=?";
        return jdbcTemplate.update(sql,goodsno);
    }

}
